package dnl.toolbox.dto;

/**
 * A simple, yet powerfull, converter that uses reflection to copy properties
 * that have the same name in <code>classA</code> and <code>classB</code>.
 * 
 * @author daniel
 * 
 */
public class DynamicConverter extends DtoConverter {

	private Class<?> classA;

	private Class<?> classB;

	public DynamicConverter(Class<?> domainClass, Class<?> dtoClass) {
		this.classA = domainClass;
		this.classB = dtoClass;
	}

	@Override
	public Class<?> getClassA() {
		return classA;
	}

	@Override
	public Class<?> getClassB() {
		return classB;
	}

	@Override
	public Object convert(Object obj, ConversionContext context) {
		Class<?> sourceClass = null;
		Class<?> targetClass = null;
		if (obj.getClass().equals(classA)) {
			sourceClass = classA;
			targetClass = classB;
		} else {
			sourceClass = classB;
			targetClass = classA;
		}
		if (sourceClass.isEnum()) {
			Object[] enumConstants = targetClass.getEnumConstants();
			for (Object object : enumConstants) {
				if (object.toString().equals(obj.toString()))
					return object;
			}
		}
		try {
			Object newInstance = targetClass.newInstance();
			context.registerConvertedObject(obj, newInstance);
			context.getContextConversions().copy(obj, newInstance, context);
			return newInstance;
		} catch (Exception e) {
			throw new IllegalStateException("Exception converting " + obj, e);
		}
	}
}
